package io.adminboot.service.impl;

import io.adminboot.entity.SysUserToken;
import io.adminboot.repository.SysUserTokenMapper;
import io.adminboot.service.SysUserTokenService;
import io.adminboot.system.oauth2.TokenGenerator;
import io.adminboot.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service("sysUserTokenService")
public class SysUserTokenServiceImpl implements SysUserTokenService {

	@Autowired
	private SysUserTokenMapper mapper;

	// 12小时后过期
	private final static int EXPIRE = 3600 * 12;

	@Override
	public R createToken(long userId) {
		// 生成一个token
		String token = TokenGenerator.generateValue();

		// 当前时间
		Date now = new Date();
		// 过期时间
		Date expireTime = new Date(now.getTime() + EXPIRE * 1000);

		// 判断是否生成过token
		SysUserToken tokenEntity = mapper.selectByPrimaryKey(userId);
		if (tokenEntity == null) {
			tokenEntity = new SysUserToken();
			tokenEntity.setUserId(userId);
			tokenEntity.setToken(token);
			tokenEntity.setUpdateTime(now);
			tokenEntity.setExpireTime(expireTime);

			// 保存token
			mapper.insert(tokenEntity);
		} else {
			tokenEntity.setToken(token);
			tokenEntity.setUpdateTime(now);
			tokenEntity.setExpireTime(expireTime);

			// 更新token
			mapper.updateByPrimaryKey(tokenEntity);
		}

		R r = R.ok().put("token", token).put("expire", EXPIRE);

		return r;
	}

	@Override
	public void logout(long userId) {
		// 生成一个token
		String token = TokenGenerator.generateValue();

		// 修改token
		SysUserToken tokenEntity = new SysUserToken();
		tokenEntity.setUserId(userId);
		tokenEntity.setToken(token);
		mapper.updateByPrimaryKey(tokenEntity);
	}
}
